﻿using UnityEngine;
using System.Collections;

public class Gun : MonoBehaviour {

	public GameObject bulletPrefab;
	public Transform launchPosition;
	public float launchRate;
	public float bulletSpeed;

	//upgrade
	public bool isUpgrade;
	public float upgradeTime;
	private float currentTime;

	//audio
	private AudioSource audioSource;


	// Use this for initialization
	void Start () {
		audioSource = GetComponent<AudioSource> ();
	}
	
	// Update is called once per frame
	void Update () {
		if (Input.GetButtonDown ("Fire1")) {
			if (!IsInvoking ("FireBullet")) {
				InvokeRepeating ("FireBullet", 0.0f, launchRate);
			}
		} else if (Input.GetButtonUp ("Fire1")) {
			CancelInvoke ("FireBullet");
		}

		currentTime += Time.deltaTime;
		if (currentTime > upgradeTime && isUpgrade) {
			isUpgrade = false;
		}
	}

	void FireBullet() {
		Rigidbody bullet = CreateBullet ();
		bullet.velocity = transform.forward * bulletSpeed;

		if (isUpgrade) {
			Rigidbody bullet2 = CreateBullet ();
			bullet2.velocity = (transform.right + transform.forward / 0.5f) * bulletSpeed;

			Rigidbody bullet3 = CreateBullet ();
			bullet3.velocity = (-transform.right + transform.forward / 0.5f) * bulletSpeed;

			//play spund
			audioSource.PlayOneShot (SoundManager.Instance.upgradedGunFire);
		} else {
			//play spund
			audioSource.PlayOneShot (SoundManager.Instance.gunFire);
		}
	}

	private Rigidbody CreateBullet() {
		GameObject bulletObject = Instantiate (bulletPrefab, launchPosition.position, Quaternion.identity) as GameObject;
		return bulletObject.GetComponent<Rigidbody> ();
	}

	public void UpgradeGun() {
		isUpgrade = true;
		currentTime = 0;
	}
}

